package 力扣链表;

public class Leedcode234回文链表 {


    public static void main(String[] args) {
//        ListNode node5 = new ListNode(1,null);
        ListNode node4 = new ListNode(1,null);
        ListNode node3 = new ListNode(2,node4);
        ListNode node2 = new ListNode(2,node3);
        ListNode node1 = new ListNode(1,node2);
        System.out.println(isPalindrome(node1));
    }


    //方法1：先全部反转，在全部比较
    public boolean isPalindrome1(ListNode head) {
        ListNode node = reverseList(head);
        while (head != null){
            if (head.val != node.val){
                return false;
            }
            node = node.next;
            head = head.next;
        }
        return true;
    }
    public ListNode reverseList1(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        //方法1.临时节点
        ListNode dummyHead = new ListNode();
        //链表的第一个节点已经在新链表中
        while (head != null){
            //开始执行新的链表
            ListNode node = new ListNode(head.val);
            node.next = dummyHead.next;
            dummyHead.next = node;
            head = head.next;
        }
        return dummyHead.next;
    }

    //方法2：先快慢指针，在逆转后一半链表
    public static boolean isPalindrome(ListNode head) {
        ListNode middleNode = middleNode(head);
        ListNode node = reverseList(middleNode);
        while (node != null){
            if (node.val != head.val){
                return  false;
            }
            head = head.next;
            node = node.next;
        }
        return true;
    }

    public static ListNode middleNode(ListNode head){
        ListNode frs = head,sec = head;
        while (sec != null && sec.next != null){
            frs = frs.next;
            sec = sec.next.next;
        }
        return frs;
    }

    public static ListNode reverseList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode node = head.next;
        ListNode newNode = reverseList(head.next);
        node.next = head;
        head.next = null;
        return newNode;
    }
}
